import * as React from "react";
import { Component } from "react";

/**
 * setState的同步异步问题
 * 异步：
 *  1.组件生命周期
 *  2.React合成事件中
 * 同步：
 *  1.原生事件中
 *  2.setTimeout中
 * @description
 * @author luyaxiang
 * @date 2021/11/10
 * @export
 * @class SetStatePage
 * @extends {Component}
 */
export default class SetStatePage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
    };
  }

  componentDidMount() {
    document.getElementById("host").addEventListener(
      "click",
      //// 即react-reconciler/src/ReactFiberWorkLoop.js batchedUpdates
      // //() => ReactDOM.unstable_batchedUpdates(this.changeCount), // 如果希望这个方法是异步的，可以使用ReactDOM.unstable_batchUpdates方法包裹来强制批处理
      this.changeCount
    );
  }

  changeCount = () => {
    const { count } = this.state;
    debugger
    this.setState({
      count: count + 1,
    }, () => {
      console.info("回调里打印", this.state.count);
    });
    console.log("改变count", this.state.count);

    // ReactDOM.flushSync(() => {
    // this.setState({
    //   count: count + 2,
    // });
    // });
  };

  changeCountWithSetTimeout = () => {
    setTimeout(() => {
      // this.changeCount(); // setState
    }, 0);
  };

  render() {
    const { count } = this.state;
    return (
      <div>
        <h3>SetStatePage</h3>
        <p>count: {count}</p>
        <button onClick={this.changeCount}>合成事件(异步)</button>

        <button onClick={this.changeCountWithSetTimeout}>
          合成事件 setTimeout(同步)
        </button>

        <button id="host">原生事件(同步)</button>
      </div>
    );
  }
}

// export default function SetStatePage(props) {
//   const [count, setCount] = useState(0);
//   const handle = () => {
//     ReactDOM.flushSync(() => {
//       setCount(count + 1);
//     });
//     // ReactDOM.flushSync(() => {
//     //   setCount(count + 2);
//     // });
//     console.log("count", count); //sy-log
//   };

//   return (
//     <div>
//       <h3>SetStatePage</h3>
//       <button onClick={handle}>{count}</button>
//     </div>
//   );
// }
